import { defineStore } from 'pinia';
import { documentApi } from '@/services/api';

export const useDocumentStore = defineStore('document', {
  state: () => ({
    documents: [],
    currentDocument: null,
    loading: false,
    error: null,
    uploadProgress: 0,
    processingStatus: null,
  }),

  getters: {
    getDocuments: (state) => state.documents,
    getCurrentDocument: (state) => state.currentDocument,
    isLoading: (state) => state.loading,
    getError: (state) => state.error,
    getUploadProgress: (state) => state.uploadProgress,
    getProcessingStatus: (state) => state.processingStatus,
  },

  actions: {
    // 获取用户的所有文档
    async fetchDocuments() {
      this.loading = true;
      this.error = null;

      try {
        const response = await documentApi.getUserDocuments();
        this.documents = response.data;

        return { success: true, documents: this.documents };
      } catch (error) {
        this.error = error.response?.data?.message || '获取文档失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },

    // 获取单个文档详情
    async fetchDocument(documentId) {
      this.loading = true;
      this.error = null;

      try {
        const response = await documentApi.getById(documentId);
        this.currentDocument = response.data;

        return { success: true, document: this.currentDocument };
      } catch (error) {
        this.error = error.response?.data?.message || '获取文档详情失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },

    // 上传文档
    async uploadDocument(formData) {
      this.loading = true;
      this.error = null;
      this.uploadProgress = 0;

      try {
        const response = await documentApi.upload(formData, {
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round(
              (progressEvent.loaded * 100) / progressEvent.total
            );
            this.uploadProgress = percentCompleted;
          },
        });

        // 添加到文档列表
        const newDocument = response.data.document;
        if (newDocument) {
          // 确保文档对象包含所有必要的字段
          const documentWithDefaults = {
            ...newDocument,
            // 如果后端返回的某些字段为undefined，提供默认值
            fileSize: newDocument.fileSize || 0,
            cardCount: newDocument.cardCount || 0,
            status: newDocument.status || 'UPLOADED'
          };

          this.documents.unshift(documentWithDefaults); // 添加到列表开头
          this.currentDocument = documentWithDefaults;
        }

        return { success: true, document: newDocument };
      } catch (error) {
        console.error('上传文档失败:', error);
        this.error = error.response?.data?.message || '上传文档失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
        // 重置上传进度
        setTimeout(() => {
          this.uploadProgress = 0;
        }, 1000);
      }
    },

    // 处理文档
    async processDocument(id) {
      this.loading = true;
      this.error = null;

      try {
        const response = await documentApi.process(id);

        // 更新文档状态为处理中
        const docIndex = this.documents.findIndex(doc => doc._id === id);
        if (docIndex !== -1) {
          this.documents[docIndex].processingStatus = 'processing';
        }

        // 启动轮询检查处理状态
        this.startPollingDocumentStatus(id);

        return {
          success: true,
          message: response.data.message,
          document: response.data.document
        };
      } catch (error) {
        console.error('处理文档失败:', error);
        this.error = error.response?.data?.message || '处理文档失败，请稍后再试';
        return {
          success: false,
          error: this.error
        };
      } finally {
        this.loading = false;
      }
    },

    // 开始轮询检查文档处理状态
    async startPollingDocumentStatus(id) {
      // 设置轮询间隔（秒）
      const pollingInterval = 60;
      let attempts = 0;
      const maxAttempts = 60; // 最多轮询5分钟

      const checkStatus = async () => {
        try {
          console.log(`[轮询] 检查文档 ${id} 的处理状态，第 ${attempts + 1} 次尝试`);
          const response = await documentApi.getById(id);
          const document = response.data;

          console.log(`[轮询] 文档状态:`, {
            id: document._id,
            processed: document.processed,
            processingStatus: document.processingStatus,
            status: document.status
          });

          // 更新文档状态
          const docIndex = this.documents.findIndex(doc => doc._id === id);
          if (docIndex !== -1) {
            this.documents[docIndex] = {
              ...this.documents[docIndex],
              ...document
            };
          }

          // 检查处理状态
          if (document.processed && document.processingStatus === 'completed') {
            console.log(`[轮询] 文档 ${id} 处理完成，停止轮询`);
            return true;
          } else if (document.processingStatus === 'failed') {
            console.error(`[轮询] 文档 ${id} 处理失败:`, document.processingError);
            return true;
          } else if (document.processingStatus === 'processing' || !document.processed) {
            // 继续轮询
            attempts++;
            if (attempts >= maxAttempts) {
              console.warn(`[轮询] 文档 ${id} 处理超时，停止轮询`);
              return true;
            }
            return false;
          } else {
            // 其他状态（可能是旧数据）
            console.log(`[轮询] 文档 ${id} 状态不明确，停止轮询`);
            return true;
          }
        } catch (error) {
          console.error(`[轮询] 检查文档 ${id} 状态失败:`, error);
          attempts++;
          if (attempts >= maxAttempts) {
            return true;
          }
          return false;
        }
      };

      const poll = async () => {
        const done = await checkStatus();
        if (!done) {
          setTimeout(poll, pollingInterval * 1000);
        }
      };

      // 开始轮询
      setTimeout(poll, pollingInterval * 1000);
    },

    // 更新文档
    async updateDocument(documentId, documentData) {
      this.loading = true;
      this.error = null;

      try {
        const response = await documentApi.updateDocument(documentId, documentData);

        // 更新当前文档
        if (this.currentDocument && this.currentDocument._id === documentId) {
          this.currentDocument = response.data;
        }

        // 更新文档列表中的文档
        const index = this.documents.findIndex(doc => doc._id === documentId);
        if (index !== -1) {
          this.documents[index] = response.data;
        }

        return { success: true, document: response.data };
      } catch (error) {
        this.error = error.response?.data?.message || '更新文档失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },

    // 删除文档
    async deleteDocument(documentId) {
      this.loading = true;
      this.error = null;

      try {
        await documentApi.delete(documentId);

        // 从文档列表中移除
        this.documents = this.documents.filter(doc => doc._id !== documentId);

        // 如果当前文档是被删除的文档，则清空当前文档
        if (this.currentDocument && this.currentDocument._id === documentId) {
          this.currentDocument = null;
        }

        return { success: true };
      } catch (error) {
        this.error = error.response?.data?.message || '删除文档失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },

    // 获取文档的所有卡片
    async fetchDocumentCards(documentId) {
      this.loading = true;
      this.error = null;

      try {
        console.log(`[document.store] fetchDocumentCards: 开始获取文档 ${documentId} 的卡片`);
        const response = await documentApi.getDocumentCards(documentId);
        console.log(`[document.store] fetchDocumentCards: API 响应:`, response);
        
        const cards = response.data;
        console.log(`[document.store] fetchDocumentCards: 成功获取 ${cards.length} 张卡片`);

        return { success: true, cards };
      } catch (error) {
        console.error(`[document.store] fetchDocumentCards: 获取文档卡片失败:`, error);
        this.error = error.response?.data?.message || '获取文档卡片失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },

    // 重置状态
    resetState() {
      this.documents = [];
      this.currentDocument = null;
      this.loading = false;
      this.error = null;
      this.uploadProgress = 0;
      this.processingStatus = null;
    },
  },
}); 